package org.example.rzfx.task;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.extern.slf4j.Slf4j;
import org.example.rzfx.entity.SysConfig;
import org.example.rzfx.mapper.SysConfigMapper;
import org.example.rzfx.service.LogService;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.Resource;

/**
 * 日志清理定时任务
 */
@Component
@Slf4j
public class LogCleanTask {
    
    @Resource
    private LogService logService;
    
    @Resource
    private SysConfigMapper sysConfigMapper;
    
    /**
     * 清理过期日志任务（每天凌晨2点执行）
     */
    @Scheduled(cron = "0 0 2 * * ?")
    public void cleanExpiredLogs() {
        log.info("开始执行日志清理任务...");
        
        try {
            // 获取日志保留天数配置
            int retentionDays = getLogRetentionDays();
            
            // 删除过期日志
            logService.deleteExpiredLogs(retentionDays);
            
            log.info("日志清理任务完成，保留天数: {}", retentionDays);
        } catch (Exception e) {
            log.error("日志清理任务执行失败", e);
        }
    }
    
    /**
     * 获取日志保留天数配置
     */
    private int getLogRetentionDays() {
        LambdaQueryWrapper<SysConfig> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysConfig::getConfigKey, "log.retention.days");
        SysConfig config = sysConfigMapper.selectOne(wrapper);
        
        if (config != null) {
            try {
                return Integer.parseInt(config.getConfigValue());
            } catch (NumberFormatException e) {
                log.warn("日志保留天数配置格式错误，使用默认值30天");
            }
        }
        
        return 30; // 默认保留30天
    }
}

